package com.classbook.violet.baigiang6.activity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import com.classbook.violet.baigiang6.adapter.ListLessonAdapter;
import com.classbook.violet.baigiang6.adapter.ListUnitAdapter;
import com.classbook.violet.baigiang6.database.DatabaseHelper;
import com.classbook.violet.baigiang6.fragment.MFragmentAdapter;
import com.classbook.violet.baigiang6.model.ConnectionDetector;
import com.classbook.violet.baigiang6.object.GlobalVar;
import com.classbook.violet.baigiang6.subject.LessonNode;
import com.classbook.violet.baigiang6.subject.SubjectParser;
import com.classbook.violet.baigiang6.subject.UnitNode;
import com.classbook.violet.baigiang7.R;
import com.viewpagerindicator.TabPageIndicator;

import android.app.AlertDialog;
import android.app.Notification;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.MailTo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.NotificationCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.Html;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SearchView;
import android.widget.Toast;

public class MainActivity extends FragmentActivity {
	MFragmentAdapter myAdapter;
	ViewPager mPager;
	TabPageIndicator mIndicator;
	ImageView iv_menu;
	ImageView iv_refresh;
	ImageView iv_update;
	SearchView sv_search;
	RelativeLayout rl_update;
	private String URL = "http://classbook.vn/cbs/violet/download";
	DatabaseHelper db;
	private String PATH = Environment.getExternalStorageDirectory().getPath() + "/EDC/Violet/";
	SubjectParser mParser;
	int time_out = 0;
	Boolean result_update = false;
	ProgressDialog pDialog;
	
	ConnectionDetector mConnect;
	
	GlobalVar global = GlobalVar.getInstance();
	///

	@Override
	protected void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
		setContentView(R.layout.activity_main);
		mConnect = new ConnectionDetector(this);
		if (mConnect.isConnectingToInternet()){
			time_out = 0;
			new AsyncTaskUpdate().execute();
		}else{
			new AsyntaskParserXML().execute();
		}
		
		db = new DatabaseHelper(this);
		
//		creat_Folder(PATH + "THCS/Hoa hoc/Hoa hoc 8/");
//		creat_Folder(PATH + "THCS/Vat li/Vat li 8/");
		
		
		
		myAdapter = new MFragmentAdapter(getSupportFragmentManager());
		
		mPager = (ViewPager) findViewById(R.id.pager);
		mPager.setAdapter(myAdapter);
		
		mIndicator = (TabPageIndicator) findViewById(R.id.indicator);
		mIndicator.setViewPager(mPager);	
		mIndicator.setCurrentItem(0);
		
		
		mPager.setOnPageChangeListener(new OnPageChangeListener() {
			
			@Override
			public void onPageSelected(int arg0) {
				// TODO Auto-generated method stub
				Log.d("Fragment change page", myAdapter.getPageTitle(arg0).toString());
				myAdapter.getItem(arg0).getView();
				
				if (arg0 == 0){
					myAdapter = new MFragmentAdapter(getSupportFragmentManager());
					mPager.setAdapter(myAdapter);
				}
				mIndicator.setCurrentItem(arg0);
			}
			
			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onPageScrollStateChanged(int arg0) {
				// TODO Auto-generated method stub
				
			}
		});
		
		
		iv_update = (ImageView) findViewById(R.id.iv_update);
		rl_update = (RelativeLayout) findViewById(R.id.rl_update);
		rl_update.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (mConnect.isConnectingToInternet()){
					time_out = 0;
					new AsyncTaskUpdate().execute();
				}else{
					AlertDialog.Builder al_connect = new AlertDialog.Builder(MainActivity.this);
					al_connect.setTitle("Không có kết nối");
					al_connect.setMessage("Bật wifi hoặc 3G để cập nhật");
					
					al_connect.setNegativeButton("OK",new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,int id) {
							dialog.cancel();
						}
					});
					al_connect.show();
				}
			}
		});
	}
	
	public class AsyncTaskUpdate extends AsyncTask<String, String, Boolean>{
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(MainActivity.this);
			pDialog.setMessage("Đang cập nhật dữ liệu ... ");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}
		
		@Override
		protected Boolean doInBackground(String... params) {
			// TODO Auto-generated method stub
			final Boolean result;
						try{
							URL url = new URL(URL + "?filename=" + "THCS/EDC_Library_7.xml");
							final HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

							urlConnection.setRequestMethod("POST");
							urlConnection.addRequestProperty("authorization", "Violet@2013");
							urlConnection.connect();
							
							File new_file = new File(PATH + "EDC_Library_7.xml");
							if (!new_file.exists()) {
							    try {
							    	new_file.createNewFile();
							    } catch (IOException e) {
							        e.printStackTrace();
							    }
							}
							
							FileOutputStream fileOutput = new FileOutputStream(new_file);
							InputStream inputStream = urlConnection.getInputStream();
							byte[] buffer = new byte[1024];
							int bufferLength = 0;
							while ((bufferLength = (inputStream.read(buffer))) > 0 ){
								fileOutput.write(buffer, 0, bufferLength);
								if (time_out > 3000){
									Log.e("UPDATE", "FAIL");
									pDialog.cancel();
									Thread.interrupted();
									
								}
							}
							if (time_out < 3000){
								Thread.interrupted();
								result_update = true;
							}else {
								Thread.interrupted();
								result_update = false;
							}
							
						}catch(Exception e){
							Thread.interrupted();
							Log.e("ERROR UPDATE", e.toString());
							result_update = false;
						}
					
			return result_update;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			pDialog.cancel();
//			if (result){
//				Log.i("RESULT UPDATE MAINACTIVITY", "success" );
//				AlertDialog.Builder al_update = new AlertDialog.Builder(MainActivity.this);
//				al_update.setTitle("Cập nhật thành công");
//				
//				al_update.setNegativeButton("OK",new DialogInterface.OnClickListener() {
//					public void onClick(DialogInterface dialog,int id) {
//						dialog.cancel();
//						new AsyntaskParserXML().execute();
//					}
//				});
//				al_update.show();
//				myAdapter = new MFragmentAdapter(getSupportFragmentManager());
//				mPager.setAdapter(myAdapter);
//				mIndicator.setCurrentItem(0);
//			}else {
//				Log.i("RESULT UPDATE MAINACTIVITY", "fail" );
//				AlertDialog.Builder al_update = new AlertDialog.Builder(MainActivity.this);
//				al_update.setTitle("Cập nhật thất bại");
//				
//				al_update.setNegativeButton("OK",new DialogInterface.OnClickListener() {
//					public void onClick(DialogInterface dialog,int id) {
//						dialog.cancel();
//						new AsyntaskParserXML().execute();
//					}
//				});
//				al_update.show();
//			}
			Log.v("UPDATE Result", "" + result);
			if (result){
				Toast.makeText(MainActivity.this, "Cập nhật thành công", Toast.LENGTH_SHORT).show();
			}else {
				Toast.makeText(MainActivity.this, "Cập nhật thất bại", Toast.LENGTH_SHORT).show();
			}
			new AsyntaskParserXML().execute();
		}
		
	}
	
	public class AsyntaskLoadMenu extends AsyncTask<String, String, Boolean>{

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(MainActivity.this);
			pDialog.setMessage("Reloading...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}
		
		@Override
		protected Boolean doInBackground(String... params) {
			// TODO Auto-generated method stub
			myAdapter = new MFragmentAdapter(getSupportFragmentManager());
			return null;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			mPager.setAdapter(myAdapter);
			pDialog.cancel();
			
		}
		
	}
	
	public class AsyntaskParserXML extends AsyncTask<String, String, Boolean>{

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(MainActivity.this);
			pDialog.setMessage("Đọc dữ liệu...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}
		
		@Override
		protected Boolean doInBackground(String... params) {
			// TODO Auto-generated method stub
			try {
				InputStream is;
				if (new File(PATH + "EDC_Library_7.xml").exists()){
					is = new FileInputStream(PATH + "EDC_Library_7.xml");
				}else{
					is = getResources().getAssets().open("EDC_Library_7.xml");
				}
				mParser = new SubjectParser(is);
			}catch (Exception e){
				Log.e("PARSER XML", e.toString());
				mParser.isParser = false;
			}
			Log.i("IsParserSuccess", "" + mParser.IsParserSuccess());
			if (!mParser.isParser){
				AlertDialog.Builder al_connect = new AlertDialog.Builder(MainActivity.this);
				al_connect.setTitle("Lỗi đọc XML");
				al_connect.setMessage(mParser.error);
				
				al_connect.setNegativeButton("OK",new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,int id) {
						new File(PATH + "EDC_Library_7.xml").delete();
						dialog.cancel();
						new AsyntaskParserXML().execute();
					}
				});
				al_connect.show();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			mPager.setAdapter(myAdapter);
			pDialog.cancel();
			
		}
		
	}
	
	public SubjectParser getParser(){
		return mParser;
	}
	
	private boolean isExternalStorageAvailable() {

        String state = Environment.getExternalStorageState();
        boolean mExternalStorageAvailable = false;
        boolean mExternalStorageWriteable = false;

        if (Environment.MEDIA_MOUNTED.equals(state)) {
            // We can read and write the media
            mExternalStorageAvailable = mExternalStorageWriteable = true;
        } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
            // We can only read the media
            mExternalStorageAvailable = true;
            mExternalStorageWriteable = false;
        } else {
            // Something else is wrong. It may be one of many other states, but
            // all we need
            // to know is we can neither read nor write
            mExternalStorageAvailable = mExternalStorageWriteable = false;
        }

        if (mExternalStorageAvailable == true
                && mExternalStorageWriteable == true) {
            return true;
        } else {
            return false;
        }
    }
	
	public void creat_Folder (String path){
		
		Log.i("CREAT FOLDER", path);
		File mFolder = new File(path);
		if (!mFolder.exists()){
			try {
		    	
				mFolder.createNewFile();
		    } catch (IOException e) {
		        e.printStackTrace();
		    }
		}
	}

}
